import {Tabs} from 'antd'
import React, {
	forwardRef,
	useEffect,
	useImperativeHandle,
	useState,
} from 'react'
import styles from './index.less'
import ParticipantsTable from './ParticipantsTable'
import AttachmentTable from './AttachmentTable'
import {DataSourceType} from '../data.t'
import {getPublicDownloadUrl} from '@/service/common/upload'
import OperationRecord from '@/components/OperationRecord'

type propsType = {
	type: string
	data: any
	id: string
}

const planDetails = (props: propsType, ref: any) => {
	const {type, data, id} = props
	// 参与人数据
	const [dataList, setDataList] = useState<any>([])
	const [attachmentData, setAttachmentData] = useState<
		readonly DataSourceType[]
	>([])

	useEffect(() => {
		setDataList(data?.personList)
		const urls: any[] = []
		const annexList = data?.annexList?.map(
			(item: {name: any; url: any}) => {
				urls.push(Number(item?.url))
				return {
					name: item?.name,
					url: item?.url,
				}
			},
		)
		if (urls?.length) {
			getPublicDownloadUrl(urls).then((result: any) => {
				if (result?.success) {
					const newAnnexList = [...annexList]
					newAnnexList?.forEach((item: {url: any}, index) => {
						const urlData = result?.data?.find(
							(items: {id: number}) =>
								items?.id === Number(item?.url),
						)
						if (urlData) {
							annexList[index].href = urlData?.url
							annexList[index].urlName = urlData?.filename
						}
					})
				}
			})
		}
		setAttachmentData(annexList)
	}, [data])

	useImperativeHandle(ref, () => ({
		getData: () => ({
			annexList: attachmentData,
			personList: dataList,
		}),
	}))

	const tabItem = [
		{
			label: '参与人',
			key: '参与人',
			children: (
				<ParticipantsTable
					type={type}
					data={dataList}
					setDataList={setDataList}
				/>
			),
		},
		{
			label: '盘点反馈附件',
			key: '盘点反馈附件',
			children: (
				<AttachmentTable
					type={type}
					attachmentData={attachmentData}
					setAttachmentData={setAttachmentData}
				/>
			),
		},
	]
	if (type === 'view') {
		tabItem.push({
			label: '操作记录',
			key: '操作记录',
			children: <OperationRecord businessId={id} businessType={25} />,
		})
	}
	return (
		<div className={styles.planDetails}>
			<Tabs type="card" defaultActiveKey="基础信息" items={tabItem} />
		</div>
	)
}
export default forwardRef(planDetails)
